Skip to content

feat(mergeProps): utility to merge component props and global config #645

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

guoyunhe
Copy link
Contributor

@guoyunhe guoyunhe commented Jun 15, 2025

用通用的语法来取代目前组件中各种手动合并 props 的代码,减少代码量,更易读。

const { className, classNames, style, styles } = mergeProps(context, props);

Summary by CodeRabbit

  • 新功能
    • 新增了 mergeProps 工具函数,用于合并多个对象属性,后传入的对象属性会覆盖前面的属性。
  • 测试
    • 添加了针对 mergeProps 函数的单元测试,验证对象属性合并的正确性。

Copy link

vercel bot commented Jun 15, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
util ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 25, 2025 2:57am

Copy link

coderabbitai bot commented Jun 15, 2025

Walkthrough

本次变更新增了一个 mergeProps 工具函数及其单元测试,并在主入口文件中导出该函数。mergeProps 支持将三个对象按优先级顺序合并,后者属性会覆盖前者。此次提交未修改其他现有逻辑或导出。

Changes

文件/分组 变更摘要
src/mergeProps.ts 新增 mergeProps 默认导出函数,实现三个对象的浅合并。
src/index.ts 新增 mergeProps 的导出。
tests/mergeProps.test.ts 新增 mergeProps 的单元测试,验证属性合并及优先级覆盖逻辑。

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant mergeProps

    Caller->>mergeProps: mergeProps(defaultProps, config, props)
    mergeProps-->>Caller: 返回合并后的对象(props > config > defaultProps)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 分钟

Poem

兔子写了个合并法,
三份属性不再怕。
浅浅一层 spread 展,
谁在后面谁说话。
测试验证没偏差,
代码整洁乐哈哈!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/mergeProps.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react".

(The package "eslint-plugin-react" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react@latest --save-dev

The plugin "eslint-plugin-react" was referenced from the config file in ".eslintrc.js » /node_modules/.pnpm/@umijs[email protected]/node_modules/@umijs/fabric/dist/eslint.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

src/index.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react".

(The package "eslint-plugin-react" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react@latest --save-dev

The plugin "eslint-plugin-react" was referenced from the config file in ".eslintrc.js » /node_modules/.pnpm/@umijs[email protected]/node_modules/@umijs/fabric/dist/eslint.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

tests/mergeProps.test.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react".

(The package "eslint-plugin-react" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react@latest --save-dev

The plugin "eslint-plugin-react" was referenced from the config file in ".eslintrc.js » /node_modules/.pnpm/@umijs[email protected]/node_modules/@umijs/fabric/dist/eslint.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (2)
src/mergeProps.ts (1)

12-18: 对象检测逻辑与递归调用混淆

mergeClassName 内部用 typeof x === 'object' 判断是否进入 mergeClassNames,但这同时把 nullarrayDate 等也算进去。考虑改用 isPlainObject 判断可避免误判;或直接信赖父函数的 classNames 键已明确限定。

tests/mergeProps.test.ts (1)

34-55: 建议增加“三对象合并”用例

当前仅验证两对象场景。由于实现对三个及以上对象采用递归策略,最好补充类似:

expect(
  mergeProps(
    { className: 'a' },
    { className: 'b' },
    { className: 'c' },
  ),
).toEqual({ className: 'a b c' });

可防止未来修改递归逻辑导致回归。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2880228 and 972fc07.

📒 Files selected for processing (4)
  • package.json (1 hunks)
  • src/index.ts (1 hunks)
  • src/mergeProps.ts (1 hunks)
  • tests/mergeProps.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/mergeProps.test.ts (1)
src/mergeProps.ts (1)
  • mergeProps (20-38)
🔇 Additional comments (1)
src/index.ts (1)

3-3: 公开导出 👍

mergeProps 暴露在入口处符合本次 PR 目标,方便外部直接引用。

package.json Outdated
Comment on lines 41 to 42
"classnames": "^2.5.1",
"is-plain-object": "^5.0.0",
"react-is": "^18.2.0"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

is-plain-object 需要默认导入,否则运行时会是 undefined

is-plain-object 采用 CommonJS 导出方式(module.exports = fn),在 ESM/TS 中通常通过默认导入获得函数实例。当前包以命名导入形式引用,将导致 isPlainObjectundefined,进而在 mergeProps 中触发运行时异常。

请在 src/mergeProps.ts 内改为默认导入,或在此处添加 @types/is-plain-object 并更新导入方式。参考补丁见下方代码评论。

🤖 Prompt for AI Agents
In package.json around lines 41 to 43, the dependency "is-plain-object" is
listed but the import usage in the code is incorrect due to its CommonJS export
style. To fix this, ensure that in src/mergeProps.ts the import of
"is-plain-object" is changed to a default import rather than a named import, or
alternatively add the @types/is-plain-object package and update the import
accordingly to avoid runtime undefined errors.

Comment on lines 1 to 2
import classNames from 'classnames';
import { isPlainObject } from 'is-plain-object';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

修正 is-plain-object 的导入方式

-import { isPlainObject } from 'is-plain-object';
+import isPlainObject from 'is-plain-object';

如前所述,is-plain-object 采用默认导出,命名导入将拿到 undefined

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import classNames from 'classnames';
import { isPlainObject } from 'is-plain-object';
import classNames from 'classnames';
import isPlainObject from 'is-plain-object';
🤖 Prompt for AI Agents
In src/mergeProps.ts at lines 1 to 2, the import of isPlainObject from
'is-plain-object' is incorrect because the package uses a default export. Change
the import statement to use a default import instead of a named import to
correctly import the function.

Comment on lines 26 to 34
Object.keys(list[1]).forEach(key => {
if (key === 'className') {
result[key] = classNames(result[key], list[1][key]);
} else if (key === 'classNames') {
result[key] = mergeClassNames(result[key], list[1][key]);
} else if (isPlainObject(list[1][key])) {
result[key] = mergeProps(result[key], list[1][key]);
} else {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

递归合并时基对象可能为 undefined,需降级为空对象

-      } else if (isPlainObject(list[1][key])) {
-        result[key] = mergeProps(result[key], list[1][key]);
+      } else if (isPlainObject(list[1][key])) {
+        result[key] = mergeProps(result[key] ?? {}, list[1][key]);

result[key] 尚未定义,直接展开会抛错。

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Object.keys(list[1]).forEach(key => {
if (key === 'className') {
result[key] = classNames(result[key], list[1][key]);
} else if (key === 'classNames') {
result[key] = mergeClassNames(result[key], list[1][key]);
} else if (isPlainObject(list[1][key])) {
result[key] = mergeProps(result[key], list[1][key]);
} else {
Object.keys(list[1]).forEach(key => {
if (key === 'className') {
result[key] = classNames(result[key], list[1][key]);
} else if (key === 'classNames') {
result[key] = mergeClassNames(result[key], list[1][key]);
} else if (isPlainObject(list[1][key])) {
result[key] = mergeProps(result[key] ?? {}, list[1][key]);
} else {
// …
}
});
🤖 Prompt for AI Agents
In src/mergeProps.ts around lines 26 to 33, when recursively merging properties,
the base object result[key] might be undefined, causing errors when passed to
mergeProps. To fix this, ensure result[key] is defaulted to an empty object if
undefined before passing it to mergeProps, preventing runtime exceptions during
recursive merging.

Comment on lines 4 to 11
function mergeClassNames<T>(classNamesA: T, classNamesB: T): T {
const result = { ...classNamesA };
Object.keys(classNamesB).forEach(key => {
result[key] = mergeClassName(classNamesA[key], classNamesB[key]);
});
return result;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

mergeClassNames 未对 undefined 做保护,传播时会崩溃

result[key] 初始为 undefined(最常见场景是只有第二个对象携带 classNames)时,{ ...classNamesA } 会抛出 TypeError。

-function mergeClassNames<T>(classNamesA: T, classNamesB: T): T {
-  const result = { ...classNamesA };
-  Object.keys(classNamesB).forEach(key => {
+function mergeClassNames<T extends Record<string, any>>(
+  classNamesA: T = {} as T,
+  classNamesB: T = {} as T,
+): T {
+  const result: Record<string, any> = { ...classNamesA };
+  Object.keys(classNamesB || {}).forEach(key => {
     result[key] = mergeClassName(classNamesA[key], classNamesB[key]);
   });
-  return result;
+  return result as T;
 }

这样可兼容首参缺失场景,并补全类型。

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function mergeClassNames<T>(classNamesA: T, classNamesB: T): T {
const result = { ...classNamesA };
Object.keys(classNamesB).forEach(key => {
result[key] = mergeClassName(classNamesA[key], classNamesB[key]);
});
return result;
}
function mergeClassNames<T extends Record<string, any>>(
classNamesA: T = {} as T,
classNamesB: T = {} as T,
): T {
const result: Record<string, any> = { ...classNamesA };
Object.keys(classNamesB || {}).forEach(key => {
result[key] = mergeClassName(classNamesA[key], classNamesB[key]);
});
return result as T;
}
🤖 Prompt for AI Agents
In src/mergeProps.ts around lines 4 to 10, the mergeClassNames function does not
handle undefined inputs, causing a TypeError when classNamesA is undefined. To
fix this, add checks to ensure classNamesA and classNamesB default to empty
objects if undefined before spreading or accessing their keys. This will prevent
crashes when the first argument is missing and maintain proper typing.

Comment on lines 21 to 24
if (list.length > 2) {
return mergeProps(list[0], mergeProps(...list.slice(1)));
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个是递归操作么?试试看用 ai 能不能改成 尾调用方式 (乱说的,不知道有没有用


export default function mergeProps<T>(...list: T[]): T {
if (list.length > 2) {
return mergeProps(list[0], mergeProps(...list.slice(1)));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个对 antd 没什么用。className 部分 antd 用的语义化 classNames 有自己的 hooks 封装。其他属性 merge 推荐直接用 {...A,...B} ,浏览器原生性能更好。用递归 + 解构 会产生大量的临时数组,此外多个 if else + isPlainObject 都是浪费性能的。

Copy link

codecov bot commented Jul 25, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.21%. Comparing base (ea6698f) to head (e5648a9).
Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #645      +/-   ##
==========================================
+ Coverage   90.19%   90.21%   +0.02%     
==========================================
  Files          36       37       +1     
  Lines         877      879       +2     
  Branches      285      291       +6     
==========================================
+ Hits          791      793       +2     
  Misses         84       84              
  Partials        2        2              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b4e493 and e5648a9.

📒 Files selected for processing (3)
  • src/index.ts (1 hunks)
  • src/mergeProps.ts (1 hunks)
  • tests/mergeProps.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/mergeProps.test.ts
  • src/index.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test / react component workflow

Comment on lines +1 to +7
export default function mergeProps<A, B, C>(
defaultProps: A,
config: B,
props: C,
): A & B & C {
return { ...defaultProps, ...config, ...props };
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

质疑这个抽象层的必要性

这个函数本质上就是对 {...defaultProps, ...config, ...props} 的简单封装。正如之前 zombieJ 提到的,直接使用原生展开语法性能更好,而且代码同样简洁易读。

考虑以下几点:

  1. 性能开销:增加了额外的函数调用层
  2. 过度抽象:对于如此简单的操作,封装可能带来的价值有限
  3. 直观性{...a, ...b, ...c} 的意图在代码中更加直观明确

建议重新评估这个工具函数是否真的能带来足够的价值来justify其存在。

🤖 Prompt for AI Agents
In src/mergeProps.ts lines 1 to 7, the mergeProps function is a simple wrapper
around the object spread syntax, which adds unnecessary abstraction and function
call overhead. To fix this, remove the mergeProps function entirely and replace
its usage with direct object spread expressions like {...defaultProps,
...config, ...props} in the codebase to improve performance and maintain code
clarity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants